//global sumstats_start \begin{threeparttable}[b] \begin{tabular}{l | l l | l l |l  l|}\hline\hline  & \multicolumn{2}{c}{\bf $ log(exp) $} & \multicolumn{2}{c}{\bf $ log(exp+1) $} & \multicolumn{2}{c}{\bf $ asinh(exp) $}\\\hline  $ \beta_{DID} $  & UV & MV & UV & MV & UV & MV \\\hline
global sumstats_start \begin{threeparttable}[b] \begin{tabular}{l | l l l}\hline\hline  $ \beta_{DID} $ & \bf $ log(exp) $ & \bf $ log(exp+1) $ & \bf $ asinh(exp) $ \\\hline 
global sumstats_end  \hline \end{tabular} \begin{tablenotes} \item {\footnotesize \tablenote}  \item {\footnotesize \$^{*}p<0.10, ^{**}p<0.05, ^{***}p<0.01\$} \end{tablenotes} \end{threeparttable}
cap file close fh
file open fh using "${path}tables/DIDOccupations.tex", write replace
file write fh "$sumstats_start" _n

preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)

/*** Separate tables per occupation type ***/
//Count elements of global typelist
//global typelist_noct = subinstr("$typelist", "mig_ct ", "",.)
//local number_types : list sizeof global(typelist_noct)
local number_types : list sizeof global(typelist)
local i = 1
foreach type of global typelist {
    qui ds mig_rm_ls00_`type'_*, not(varl *mis*)
    local vlist = r(varlist)
    local treatlist = ""
    foreach v of local vlist {
        local vlabel: variable label `v'
        local lab = substr("`v'",13,.)
        local treatlab = subinstr("`lab'","_","",.)
        g treat`treatlab' = asinh(mig_rm_ls00_`lab')
        label var treat`treatlab' "`vlabel'"
        local treatlist "`treatlist' treat`treatlab'"
    }
    foreach v in lnexp lnexpplus1 asinhexp {
        foreach tr of local treatlist {
            eststo, title(`v'): qui reghdfe `v' c.`tr'#c.$after  if $didsample, $rhsoptions
            local trl = subinstr("`tr'", "treat", "", .)
            local bOne`v'`trl' = _b[c.`tr'#c.$after]
            local seOne`v'`trl' = _se[c.`tr'#c.$after]
            local stOne`v'`trl' = ""
            if `bOne`v'`trl''/`seOne`v'`trl''>=1.645 {
                local stOne`v'`trl' = "*" 
            }
            if `bOne`v'`trl''/`seOne`v'`trl''>=1.96 {
                local stOne`v'`trl' = "**" 
            }
            if `bOne`v'`trl''/`seOne`v'`trl''>=2.576 {
                local stOne`v'`trl' = "***" 
            }
        }
        
        eststo, title(`v'): qui reghdfe `v' c.(`treatlist')#c.$after   if $didsample, $rhsoptions
        local cnum = 1
        local totchars : list sizeof local(treatlist)
        matrix A`type'_`v' = J(`totchars',6,.)       
        foreach tr of local treatlist {
            local trl = subinstr("`tr'", "treat", "", .)
            local bAll`v'`trl' = _b[c.`tr'#c.$after]
            local seAll`v'`trl' = _se[c.`tr'#c.$after]
            local stAll`v'`trl' ""
            if `bAll`v'`trl''/`seAll`v'`trl''>=1.645 {
                local stAll`v'`trl' = "*" 
            }
            if `bAll`v'`trl''/`seAll`v'`trl''>=1.96 {
                local stAll`v'`trl' = "**" 
            }
            if `bAll`v'`trl''/`seAll`v'`trl''>=2.576 {
                local stAll`v'`trl' = "***" 
            }
            matrix A`type'_`v'[`cnum',1]=_b[c.`tr'#c.$after]
            matrix A`type'_`v'[`cnum',2]=_se[c.`tr'#c.$after]
            qui su `tr' if e(sample)
            matrix A`type'_`v'[`cnum',3]=r(mean)
            matrix A`type'_`v'[`cnum',4]=r(sd)
            qui g `tr'_nolog = sinh(`tr')
            qui su `tr'_nolog if e(sample)
            matrix A`type'_`v'[`cnum',5]=r(mean)
            matrix A`type'_`v'[`cnum',6]=r(sd)
            drop `tr'_nolog
            local cnum = `cnum'+1
        }
        matrix rownames A`type'_`v' = `treatlist'
    }
    foreach tr of local treatlist {
        local vlabel: variable label `tr'
        di "`vlabel'"
        local tr = subinstr("`tr'", "treat", "", .)
        //file write fh "`tr'" "&" %9.3f (`bOnelnexp`tr'') "`stOnelnexp`tr''"  "&" %9.3f (`bAlllnexp`tr'') "`stAlllnexp`tr''"  "&"  %9.3f (`bOnelnexpplus1`tr'') "`stOnelnexpplus1`tr''"  "&"  %9.3f (`bAlllnexpplus1`tr'') "`stAlllnexpplus1`tr''"  "&" %9.3f (`bOneasinhexp`tr'') "`stOneasinhexp`tr''"  "&" %9.3f (`bAllasinhexp`tr'') "`stAllasinhexp`tr''"  "\\" _n
        file write fh "`vlabel'" "&" %9.3f (`bAlllnexp`tr'') "`stAlllnexp`tr''"  "&"   %9.3f (`bAlllnexpplus1`tr'') "`stAlllnexpplus1`tr''"  "&" %9.3f (`bAllasinhexp`tr'') "`stAllasinhexp`tr''"  "\\" _n
        file write fh "" "&" "(" %9.3f (`seAlllnexp`tr'') ")" "&" "("  %9.3f (`seAlllnexpplus1`tr'') ")" "&" "(" %9.3f (`seAllasinhexp`tr'') ")"  "\\" _n
     }
    file write fh "\hline" _n
    estout, $estout_params_txt drop()
    //We exclude mig_ct from this one, so we start exporting tables for i==2 and on
    if `i'==2 {
            estout using "${path}tables/DIDMainCumExp_Occupations.tex", replace $estout_params $estout_pre_panelA
        }
    if `i'>2 & `i'<`number_types' {
        estout using "${path}tables/DIDMainCumExp_Occupations.tex", append $estout_params $estout_pre_panelB
    }
    if `i' == `number_types' {
        estout using "${path}tables/DIDMainCumExp_Occupations.tex", append $estout_params $estout_pre_panelB $estout_post
    }
    eststo clear
    local i  = `i'+1
}
restore
file write fh "$sumstats_end" _n
file close fh

/*** Tables and figures for all occupation types, INCLUDING the original (simple count) for comparison purposes ***/
foreach v in lnexp lnexpplus1 asinhexp {
    local typegroup = 1
    foreach type of global typelist {
        preserve
        qui ds mig_rm_ls00_`type'_*, not(varl *mis*)
        local vlist = r(varlist)
        local treatlist = ""
        local treatlabels = ""
        foreach var of local vlist {
            local vlab: variable label `var'
            local lab = substr("`var'",13,.)
            local treatlab = subinstr("`lab'","_","",.)
            g treat`treatlab' = asinh(mig_rm_ls00_`lab')
            local treatlist "`treatlist' `treatlab'"
            local treatlabels "`treatlabels'  `vlab' |"
        }
        clear
        qui svmat A`type'_`v'

        ren A`type'_`v'1 beta
        ren A`type'_`v'2 se
        ren A`type'_`v'3 lnvarmean
        ren A`type'_`v'4 lnvarse
        ren A`type'_`v'5 varmean
        ren A`type'_`v'6 varse
        
        qui g label = ""
        local Nleng = length("`treatlabels'")
        forvalues n=1/`Nleng' {
            //di "`treatlabels'"
            local pos = strpos("`treatlabels'","|")-1
            local title = trim(substr("`treatlabels'",1,`pos'-1))
            local treatlabels = trim(substr("`treatlabels'",`pos'+2,.))
            //di "`title'"
            qui replace label = "`title'" if _n==`n'
            local n = `n'+1
        }

        g group = `typegroup'

        tempfile matA`type'
        save `matA`type'', replace
        restore

        local typegroup = `typegroup'+1
    }
    preserve
    clear
    foreach type of global typelist {
        append using `matA`type''
    }

    g n = _n
    g i = n+(group-1)
    
    g onepersonpc = 1/varmean //This computes the % that represents 1 person in the sample for average industry
    g meoneperson = beta*onepersonpc //Multiplying this by the elasticity can be interpreted as `one person' increase.
    g meoneperson_ul = (beta+1.645*se)*onepersonpc
    g meoneperson_ll = (beta-1.645*se)*onepersonpc

    //Compute the meoneperson for the baseline result
    g temp = meoneperson if i==1
    egen meoneperson_baseline = max(temp)
    drop temp
    
    //Compute Relative marginal effect (relative to baseline)
    g meonepersonR = meoneperson/meoneperson_baseline
    g meonepersonR_ul = meoneperson_ul/meoneperson_baseline
    g meonepersonR_ll = meoneperson_ll/meoneperson_baseline

    g x = i-1
    
    list, sep(20)
    g labellist = string(i) + " " + `"""' + label + `"""'
    g labellistR = string(x) + " " + `"""' + label + `"""' if x>0

    levelsof labellist, local(lablist) clean
    levelsof labellistR, local(lablistR) clean

    qui levelsof group, local(ilist)
    local twowaystr = ""
    foreach gr of local ilist {
        local twowaystr = "`twowaystr' (bar meoneperson i if group==`gr')"
        local twowaystrR = "`twowaystrR' (bar meonepersonR x if group==`gr')"
    }
    twoway `twowaystr' ///
        (rcap meoneperson_ul meoneperson_ll i), ///
            scheme(s1color) ytitle("Marginal effect (normalized)") xtitle("") legend(off) yline(0, lp(dash)) ///
                xlabel(`lablist', angle(45) notick labsize(small)) 
    graph export "${path}graphs/DIDME_`v'.eps", replace as(eps)

    twoway `twowaystrR' ///
        (rcap meonepersonR_ul meonepersonR_ll x) if x>0, ///
            scheme(s1color) ytitle("Marginal effect (relative to baseline)") xtitle("") legend(off) yline(0, lp(dash)) ///
                xlabel(`lablistR', angle(45) notick labsize(small)) ylabel(-10(5)20, grid)
    graph export "${path}graphs/DIDME_Relative_`v'.eps", replace as(eps)

    restore
}

